#include "WebPageSearcherTask.h"
#include "nlohmann/json.hpp"
#include "QueryEngine.h"
#include "LogUtils.h"
#include "CacheUtils.h"

using json = nlohmann::json;

void WebPageSearcherTask::process(){
    // 获取QueryEngine单例对象
    QueryEngine& engine = QueryEngine::getInstance();

    // 获取Redis单例对象
    CacheUtils& cache = CacheUtils::getInstance();

    // 获取网页结果
    LOG_INFO << "[WebPageSearcherQuery] [" << _msg << "]";
    
    string j_str;

    // 先查Redis是否有cache
    auto cache_result = cache.getWebPageSearcherCache(_msg);
    if(cache_result.has_value()){
        // 缓存命中
        LOG_INFO << "[WebPageSearcherQuery] [Cache Hit]";
        j_str = cache_result.value().dump();
    }else{
        // 缓存未命中
        LOG_INFO << "[WebPageSearcherQuery] [Cache Miss]";
        json j = engine.WebPageSearcher(_msg);
        j_str = j.dump();

        // 添加到缓存
        cache.addWebPageSearcherCache(_msg, j);
    }

    // 响应内容
    Message ret_msg;
    ret_msg.tag = WebPageSearcher;
    ret_msg.length = j_str.size();
    ret_msg.value = std::move(j_str);

    _con->sendInLoop(ret_msg);
}